package business;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.Transaction;

import utils.HibernateUtil;

import entities.Boek;
import entities.Lening;
import entities.Lid;
import exceptions.NoEntityException;

public class LeningAanmaker implements IEntityAanmaker<Lening>
{
	private Lening lening;
	
	private Date beginddatum;
	private Date einddatum;
	private Boek boek;
	private Lid lid;

	// Constructor
	
	public LeningAanmaker(Date begindatum, Date einddatum, Boek boek, Lid lid)
	{
		this.beginddatum = begindatum;
		this.einddatum = einddatum;
		this.boek = boek;
		this.lid = lid;
	}
	
	// Getters en Setters
	
	public Date getBeginddatum()
	{
		return beginddatum;
	}
	public void setBeginddatum(Date beginddatum)
	{
		this.beginddatum = beginddatum;
	}
	public Date getEinddatum()
	{
		return einddatum;
	}
	public void setEinddatum(Date einddatum)
	{
		this.einddatum = einddatum;
	}
	public Boek getBoek()
	{
		return boek;
	}
	public void setBoek(Boek boek)
	{
		this.boek = boek;
	}
	public Lid getLid()
	{
		return lid;
	}
	public void setLid(Lid lid)
	{
		this.lid = lid;
	}

	// Methods
	
	@Override
	public Lening createEntity()
	{
		lening = new Lening(beginddatum, einddatum, boek, lid);
		return lening;
	}

	@Override
	public boolean saveEntity()
	{
		
		try
		{
			if(lening == null)
			{
				throw new NoEntityException();
			}
		}
		catch(NoEntityException e)
		{
			e.printStackTrace();
			return false;
		}
		
		Session session = null;
		Transaction tx = null;
		
		boolean saved = true;
		
		try
		{
			// get a session
			session = HibernateUtil.getSessionFactory().openSession();
			
			// Start a tx
			tx = session.beginTransaction();
			
			session.save(lening);
			
			// Commit the changes
			tx.commit();
		}
		catch(RuntimeException e)
		{
			e.printStackTrace();
			
			if(tx != null)
				tx.rollback();
			
			// the person has not been added, so return false.
			saved = false;
		}
		finally
		{
			if(session != null)
			{
				session.close();
			}
		}	
			
		return saved;
		
	}
}
